<template>
  <div v-loading="loading" class="hello">
    <div v-show="!showShoppingCart">
        <div ref="topRef" class="flex">
            <el-upload
              action="/"
              :on-change="onChange"
              :auto-upload="false"
              :show-file-list="false"
              accept=".xls, .xlsx">
              <el-button type="primary">导入数据库</el-button>
          </el-upload>
          <el-input v-model="searchKey" placeholder="搜索关键词" @input=searchHandle></el-input>
          <el-button type="danger" v-if="shoppingCartSku.length > 0 && !showShoppingCart" @click="showShoppingCart = true">
              {{shoppingCartSku.length}}
          </el-button>
        </div>
        <productList ref="productListRef" :listShow="listShow" :height="`calc(100% - ${$refs.topRef ? $refs.topRef.offsetHeight : 0}px)`" :shoppingCartSku="shoppingCartSku" @add="add" />
    </div>

    <div v-show="showShoppingCart" class="shoppingCartSkuBox">
        <div class="center">
            <el-button type="primary" :icon="ArrowLeft" size="small" @click="showShoppingCart = false">返回列表</el-button>
            <el-button type="primary" size="small" @click="DownloadExcel">导出购物车</el-button>
            <span> 金额合计：{{ money }}</span>
        </div>
        <productList :listShow="shoppingCartList" :shoppingCartSku="shoppingCartSku" :isShopCart="true" @add="add" @remove="remove" @change="change" />
        <div>
            <span v-for="item in shoppingCartList">{{ item.sku}}:{{item.num}},</span>
        </div>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios'
import { ref, computed, getCurrentInstance, onBeforeMount } from 'vue'
import { ArrowLeft } from '@element-plus/icons-vue'
import { debounce } from 'throttle-debounce'
import * as XLSX from 'xlsx'
import { export_json_to_excel } from '../utils/Export2Excel.js'
import productList from './productList.vue'
import productList2 from './productList2.vue'

// defineOptions({ name: 'HelloWorld'})

const instance = getCurrentInstance().proxy

const topRef = ref()

const loading = ref(false)
const showShoppingCart = ref(false)
const reg1 = new RegExp("#","g")
const searchKey = ref('')
const list = ref([])
const listShow = ref([])
const shoppingCartList = ref([])
const shoppingCartSku = ref([])
const productListRef = ref([])

const money = computed(() => {
  let price = 0
  shoppingCartList.value.forEach(item => {
    price = price + (item.discount_price * item.num)
  })
  price = price * 1.06
  return price
})

onBeforeMount(async () => {
  // await getData(1)
  // await getData(2)
  // await getData(3)
  // list.value = list.value.sort((x, y) => y.price - x.price)
  // listShow.value = list.value
  // getStorageShopCart()
  
})
async function getData(page) {
  loading.value = true
  return axios({
    method: 'post',
    url: '/action.php',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: {
      category: '',
      pname: '',
      action: 'get_list',
      page: page,
      page_size: 50000
    }
  }).then(res => {
    let data = res.data.data
    data = data.map(item =>{
      const { p_discount, p_image, p_name, p_price, p_sys_price, p_sku, p_stock_remain } = item
      return {
        discount_price: p_price,
        pic: p_image,
        price: p_sys_price,
        name: p_name,
        sku: p_sku,
        stock: p_stock_remain,
        discount: p_discount * 10
      }
    })
      // data = data.sort((x, y) => y.price - x.price)
      data = data.filter(item => item.stock)
      // data.forEach(item => {
      //   const pic = item.图片链接 || `https://bullfrog.izehui.com/uploads/product/${sku.slice(0,2)}/${sku}.jpg`
      //   item.pic = pic
      //   item.discount = item.discount* 10
      // })
      list.value = list.value.concat(data)
      // listShow.value = data
      // getStorageShopCart()
  }).catch(error=> {
    instance.$message.error(error)
  }).finally(() => {
    loading.value = false
  })
}
// axios.get('http://47.108.50.135:8887/').then(res => {
 // 文件选择回调
function onChange(file, fileList) {
  // 读取数据的方法
  if (!file) {
    // 如果没有文件 - 当然也可以提醒用户弹个警告框 但是基本没有这种情况的出现
    return false
  } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
    // 文件格式的判断
    instance.$message.error("上传格式不正确，请上传xls或者xlsx格式")
    return false
  }
  const fileReader = new FileReader()
  fileReader.onload = (ev) => {
      const data = ev.target.result
      var workbook = XLSX.read(data, {
                type: 'binary'
            })
      console.log(workbook.SheetNames)
      // 取第一张表
      const wsname = workbook.SheetNames[0]
      // 生成json表格内容
      let ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
      const stocks = Object.keys(ws[0]).filter(item => item.indexOf('剩余库存') > -1)
      // https://bullfrog.izehui.com/uploads/product/QW/QW2183B.jpg
      ws = ws.map(item => {
        const sku = item.SKU码.toUpperCase()
        // const pic = item.图片链接 || `https://bullfrog.izehui.com/uploads/product/${/^(.*?)\d/.exec(sku)[1]}/${sku}.jpg`
        const pic = item.图片链接 || `https://bullfrog.izehui.com/uploads/product/${sku.slice(0,2)}/${sku}.jpg`
        return {
          discount_price: item.本次单个产品价格,
          pic,
          price: item.系统价,
          name: item.产品名称,
          sku,
          stock: item[stocks.findLast(k => k)],
          discount: item.本次折扣系数 * 10
        }
      })
      // ws = ws.filter(item => item.stock)
      ws = ws.sort((x, y) => y.price - x.price)
      list.value = ws
      listShow.value = ws
      getStorageShopCart()
  };
  // 如果为原生 input 则应是 file[0]
  fileReader.readAsBinaryString(file.raw)
}

// 搜索事件
const searchHandle = debounce(350, function(val) {
  if (!val) {
    return listShow.value = list.value
  }
  
  let skus = []
  // 以#开头则说明搜索的内容为sku，多个sku空格隔开
  if (val.indexOf('#') == 0) {
      skus = val.replace(reg1,"")
      skus = skus.split(' ')
      skus = skus.filter(s => s)
      if (skus.length === 0) {
          return true
      }
      listShow.value = list.value.filter(item => {
        if (skus.length && skus.includes(item.sku)) {
            return true
        }
        return false
      })
  } else {
    let keyswords = val.split(' ')
    keyswords = keyswords.filter(s => s)
    listShow.value = list.value.filter(item => {
      if (keyswords.some(e => item.name && item.name.includes(e) )) {
          return true
      }
      return false
    })
  }
  productListRef.value.setListElScrollTop()
})

// 购物车数量修改
function change(item) {
    setStorageShopCart()
}

// 更新购物车到stoage
function setStorageShopCart() {
    const data = {}
    shoppingCartList.value.forEach(item => {
        data[item.sku] = item.num
    })
    localStorage.removeItem('shopCart')
    localStorage.setItem('shopCart', JSON.stringify(data))
    if (shoppingCartList.value.length === 0) {
      showShoppingCart.value = false
    }
}

// 从stoage获取购物车
function getStorageShopCart() {
  let data = localStorage.getItem('shopCart')
  if (!data) {
    return false
  }
  data = JSON.parse(data)
  shoppingCartSku.value = Object.keys(data)

  let shopCartList = list.value.filter(item => shoppingCartSku.value.includes(item.sku))
  shoppingCartSku.value = shopCartList.map(item => item.sku)
  shopCartList.forEach(item => {
    item.num = data[item.sku]
  })
  shoppingCartList.value = shopCartList
  

}

// 加入购物车
function add(item) {
    if (shoppingCartSku.value.includes(item.sku)) {
        return true
    }
    shoppingCartList.value.push({...item, num: 1})
    shoppingCartSku.value.push(item.sku)
    
    setStorageShopCart()
}

// 删除购物车某一个sku
function remove(item) {
    shoppingCartList.value = shoppingCartList.value.filter(y => y.sku !== item.sku)
    shoppingCartSku.value = shoppingCartList.value.map(y => y.sku)
    setStorageShopCart()
}

// 导出excel
function DownloadExcel() {
  const list = shoppingCartList.value
  const headers = [
    { label: '', prop: '' },
    { label: 'sku', prop: 'sku' },
    { label: '数量', prop: 'num' },
    { label: '产品名称', prop: 'name' },
    { label: '购买价格', prop: 'discount_price' },
    { label: '图片链接', prop: 'pic' }
  ]

    const tHeader = headers.slice(1).map(item => {
      return item.label || item.field || item.slotName
    })

    const filterVal = headers.slice(1).map(item => {
      return item.prop || item.slotName
    })
    const data = formatJson(filterVal, list)
    const time = new Date()
    const date = time.getFullYear() + '-' + (time.getMonth() + 1 + '').padStart(2, '0') + '-' + (time.getDate() + '').padStart(2, '0')
    export_json_to_excel({
      header: tHeader,
      data,
      filename: '姓名' + date,
      bookType: 'xlsx'
    })
}

// 格式化成二维数据
function formatJson(filterVal, jsonData) {
  return jsonData.map(v => filterVal.map(j => {
    return v[j]
  }))
}
</script>

<style scoped>
.hello{
  /* max-width: 500px; */
  margin: 0 auto;
}
.shoppingCartSkuBox{
    width: 100%;
    height: 100%;
}
.flex{
    display: flex;
}
</style>
